package org.ezplatform.integ.ocr.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.system.basic.util.ConfSettingUtils;
import org.ezplatform.util.GlobalConstant;
import org.ezplatform.util.JwtUtils;
import org.ezplatform.util.RestClient;
import org.ezplatform.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OcrWebApiService {
    private static final Logger LOG = LoggerFactory.getLogger(OcrWebApiService.class);

    private static RestClient baseRestClient = new RestClient(true);

    /**
     * 连接识别服务器
     * @param url
     * @param param
     * @return
     * @throws HttpHostConnectException
     * @throws IOException
     * @throws ParseException
     */
    public static String sendPost(String url, Map<String,String> param, String funcParams) throws HttpHostConnectException,IOException,ParseException{
        String result = "";
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        String funcParamsJson = getFuncParamsJson(funcParams);
        if(StringUtils.isNotEmpty(funcParamsJson)) {
            param.put("funcParams", funcParamsJson);
        }
        String fullurl = "";
        String fileUrl = param.get("fileUrl");
        String[] fileUrls = fileUrl.split("fid=");
        String fid = "";
        if(fileUrls.length==2){
            fid = fileUrls[1].substring(0,32);
        }
        String[] fileUrlCKs = fileUrl.split("chksum=");
        String chksum = "";
        if(fileUrlCKs.length==2){
            chksum = fileUrlCKs[1].substring(0,32);
        }
        //请求参数
        for(String key:param.keySet()){
            list.add(new BasicNameValuePair(key, param.get(key)));
        }
        String appToken = param.get("appToken");
        try{
            fullurl = EntityUtils.toString(new UrlEncodedFormEntity(list, Consts.UTF_8));
        }catch (IOException e) {
            result = "{\"code\":-1,\"data\":\"\",\"error\":\"拼接url参数IO异常\",\"type\":0}";
            e.printStackTrace();
        } catch (ParseException e) {
            result = "{\"code\":-1,\"data\":\"\",\"error\":\"拼接url参数强转异常\",\"type\":0}";
            e.printStackTrace();
        }
        Map<String, String> textParams = new HashMap<String, String>();
        textParams.put("fid", fid);
        textParams.put("chksum", chksum);
        String jwtToken = JwtUtils.createJwtToken(GlobalConstant.X_APP_AUTH);
        byte[] fileBody= baseRestClient.getBytes("/cmp/attachment/download", jwtToken, textParams);
        HttpPost httppost = new HttpPost(url+"?"+fullurl);
       // httppost.setEntity(new ByteArrayEntity(fileBody));
        LOG.error("1转换ocr请求地址："+url+"?"+fullurl);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try{
            httppost.addHeader("appToken", appToken);
            CloseableHttpResponse response = httpClient.execute(httppost);
            if(response.getStatusLine().getStatusCode() == 200){
                HttpEntity entity = response.getEntity();
                result = dealResultJosn(EntityUtils.toString(entity),"0");
                LOG.error("请求成功");
            }else{
                LOG.error("转换ocr请求地址："+url+"?"+fullurl);
                result = "{\"code\":-1,\"data\":\"\",\"error\":\"转换异常\",\"type\":0}";
            }
        }catch (Exception e) {
            LOG.error("转换ocr请求地址："+url+"?"+fullurl+"===="+e.getMessage(),e);
        }finally{
            httppost.releaseConnection();
        }
        return result;

    }

    private static String getFuncParamsJson(String funcParams) {
        String funcParamJson = "";
        if(StringUtils.isNotEmpty(funcParams)) {
            funcParamJson = "{"+funcParams+"}";
        }
        return funcParamJson;
    }

    /**
     * 通过fileUrl获取文件下载全路径
     * @param fileUrl
     * @return
     */
    public String getFullFileDownloadUrl(String fileUrl) {
        WebUser user = WebUtils.getCurrentUser();
        String host = GlobalConstant.getConfig("app.flexbase.ocr.url");//解决ocr服务和base服务夸网络请求时，不需要修改base预览地址特追加的
        if(StringUtils.isEmpty(host)){
            host = GlobalConstant.getConfig("app.flexbase.attachment.url");
            if(StringUtils.isEmpty(host)) {
                //判断是否配有外网地址，如果有，则取外网地址
                String outWebPath = GlobalConstant.getConfig("app.flexbase.web.url.out");
                String webPath = GlobalConstant.getConfig("app.flexbase.web.url");
                if(!StringUtils.isEmpty(outWebPath)) {
                    host = outWebPath;
                }else {
                    host = webPath;
                }
            }
        }

        fileUrl = host+fileUrl+"&token="+user.getJwtToken();
        return fileUrl;
    }

    /**
     * 从url中获取ip和端口号
     * @param uri
     * @return
     */
    public static URI getIP(URI uri) {
        URI effectiveURI = null;
        try {
            effectiveURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null);
        } catch (Throwable var4) {
            effectiveURI = null;
        }
        return effectiveURI;
    }

    public static String dealResultJosn(String urlJsonStr,String corpId){
        LOG.debug("urlJsonStr="+urlJsonStr);
        String servicePath = ConfSettingUtils.getConfSettingValue("ocrServerPathVal", corpId);

        JSONObject urlJson = JSONObject.parseObject(urlJsonStr);
        JSONObject dataResultJson = urlJson.getJSONObject("result");
        if(dataResultJson!=null && dataResultJson.get("pdfUrl")!=null){
            String url = servicePath + dataResultJson.getString("pdfUrl").split("AIOcrCloud")[1];
            dataResultJson.put("pdfUrl",url);
        }else if(dataResultJson!=null && dataResultJson.get("ofdUrl")!=null){
            String url = servicePath + dataResultJson.getString("ofdUrl").split("AIOcrCloud")[1];
            dataResultJson.put("ofdUrl",url);
        }else{
            return urlJsonStr;
        }
        LOG.debug("urlJson = "+ JSON.toJSONString(urlJson));
        return JSON.toJSONString(urlJson);
    }


    public static String sendPost_new(String url, Map<String,String> param, String funcParams) throws HttpHostConnectException,IOException,ParseException{
        String result = "";
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        String funcParamsJson = getFuncParamsJson(funcParams);
        if(StringUtils.isNotEmpty(funcParamsJson)) {
            param.put("funcParams", funcParamsJson);
        }
        String fullurl = "";
        String fileUrl = param.get("fileUrl");
        String[] fileUrls = fileUrl.split("fid=");
        String fid = "";
        if(fileUrls.length==2){
            fid = fileUrls[1].substring(0,32);
        }
        String[] fileUrlCKs = fileUrl.split("chksum=");
        String chksum = "";
        if(fileUrlCKs.length==2){
            chksum = fileUrlCKs[1].substring(0,32);
        }
        //请求参数
        for(String key:param.keySet()){
            list.add(new BasicNameValuePair(key, param.get(key)));
        }
        String appToken = param.get("appToken");
        try{
            fullurl = EntityUtils.toString(new UrlEncodedFormEntity(list, Consts.UTF_8));
        }catch (IOException e) {
            result = "{\"code\":-1,\"data\":\"\",\"error\":\"拼接url参数IO异常\",\"type\":0}";
            e.printStackTrace();
        } catch (ParseException e) {
            result = "{\"code\":-1,\"data\":\"\",\"error\":\"拼接url参数强转异常\",\"type\":0}";
            e.printStackTrace();
        }

        String jwtToken = JwtUtils.createJwtToken(GlobalConstant.X_APP_AUTH);

        LOG.error("===============fullurl:"+fullurl);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, String> formParams = new LinkedMultiValueMap<>();
        formParams.add("appToken", appToken);
        formParams.add("fileUrl", fileUrl);

        // 封装请求头和请求体
        org.springframework.http.HttpEntity<MultiValueMap<String, String>> requestEntity = new org.springframework.http.HttpEntity<>(formParams, headers);

        //结果
        LOG.error("===============url:"+url);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        //LOG.error("===============结果"+response.getBody());
        return response.getBody();
    }

}
